package com.lu.config;

import com.google.gson.GsonBuilder;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import lombok.Setter;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

import java.net.InetSocketAddress;
import java.util.Arrays;

/**
 * @program Elasticsearch
 * @description: es jest 连接初始化配置
 * @author: zhanglu
 * @create: 2020-04-29 23:09:00
 */
@Setter
@Configuration
@ConfigurationProperties(prefix = "es.jest")
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {

    //rest服务地址
    private String url;
    //是否多线程
    private boolean multiThreaded;
    //最大连接数
    private int maxTotalConnection;
    //设置连接超时
    private int connTimeout;
    //设置读取超时
    private int readTimeout;

    @Bean
    public JestClient jestClient(){
        JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig.Builder(this.url)
                .multiThreaded(multiThreaded) //设置为多线程
                .defaultMaxTotalConnectionPerRoute(maxTotalConnection)
                .maxTotalConnection(maxTotalConnection) //最大连接数
                .connTimeout(connTimeout)  //设置连接超时
                .readTimeout(readTimeout) //设置读取超时
                .gson(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()) //设置日期的格式
                .build());
        JestClient jestClient = factory.getObject();
        return jestClient;
    }

    @Override
    public RestHighLevelClient elasticsearchClient() {
        InetSocketAddress[] inetSocketAddresses = Arrays.stream(url.split(",")).map(host -> {
            host = host.replace("http://", "");
            host = host.replace("https://", "");
            String[] split = host.split(":");
            return new InetSocketAddress(split[0], Integer.valueOf(split[1]));
        }).toArray(InetSocketAddress[]::new);
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder().connectedTo("127.0.0.1").build();
        return RestClients.create(clientConfiguration).rest();
    }

    @Bean
    public ElasticsearchRestTemplate elasticsearchRestTemplate() {
        return new ElasticsearchRestTemplate(elasticsearchClient());
    }

}
